<!--动态表单《表头和表尾》搜索组建-->
<template>
    <div class="all-search-wrapper" :id="boxId" ref="searchInput">
        <a-input ref="inputRef" v-model="inputValue" @focus="showModal" @change="inputSearch" @pressEnter="clickEnter" />
        <div class="zzc" @click="tableShow=false" v-show="tableShow"></div>
        <div class="search-wrapper" ref="searchWrapper" v-show="tableShow">
            <a-table :scroll="{x:0,y:200}" :columns="columns" :data-source="tableData" :customRow="customClick" bordered :pagination="pagination" :loading="isRun">
                <!--建议供应商-->
                <span slot="supplieType" slot-scope="text">
                    {{text==1?'客户':text==2?'供应商':'客户/供应商'}}
                </span>
                <!--建议供应商-->
                <!--客户-->
                <!-- <span slot="partnerClassCustomer" slot-scope="text">

                </span> -->
            </a-table>
        </div>
    </div>
</template>
<script>

import { getAction, postAction } from "@/api/manage";

export default {
    data () {
        return {
        }
    },
    props: {
        dynamicData: {
            type: Array,
            default: () => []
        },
        modelVal: {
            type: String,
            default: ''
        },
        value: {
            type: String,
            default: ''
        },
        changeInvoiceType: { //用于采购发票（发票搜索type:1正发票，0负发票）
            type: Number
        }
    },
    watch: {
        tableShow () {
            this.$emit('showZzc', this.tableShow);
        }
    },

    data () {
        return {
            boxId: null,             //当前容器id
            codesName: null,         //当前组建名称
            columns: [],

            pagination: {
                current: 1,
                pageSize: 10,
                total: 0,
                size: 'small',
                onChange: (page, pageSize) => {
                    // this.postData.current = page;
                    this.pagination.current = page;
                    this.pagination.pageSize = pageSize;
                    this.pageList();
                }
            },
            postData: {},
            tableData: [],
            customClick: (record, index) => ({
                on: {
                    click: (event) => {
                        event.preventDefault();
                        this.clickEnter('click', record);

                    },
                },
            }),
            tableShow: false,
            isRun: false,
            setTime: null,  //延迟请求
            id: null,       //当前选择的搜索id
            tableBody: null,
            apiUrl: null,
            inputValue: this.value,  //输入框的值
        }
    },
    created () {
        this.checkSearch();

        if (this.$route.path == '/inventory/bills/InitialInventory') {
            this.pageList('warehouse');
        }


        //发票
        if (this.$route.path == '/procurement/purchaseInvoice') {
            this.pageList('invoice');
        }
    },
    mounted () {
        document.addEventListener('click', (e) => {
            //获取弹出表格对象
            if (this.tableShow && this.boxId != null) {
                const userCon = document.getElementById(this.boxId);

                //判断表格对象中是否包含点击对象
                if (userCon && !userCon.contains(e.target)) {

                    //删除操作
                    if (this.inputValue == '') {
                        console.log(this.codesName)
                        let data = Object.assign({}, { codesName: this.codesName })
                        data.modelVal = this.modelVal;
                        this.$emit('clickItem', data);
                    } else {
                        if (this.id) {
                            let data = this.tableData.filter(item => item.id == this.id);
                            this.inputValue = data[0].name;
                        }
                    }
                    this.tableShow = false
                }
            }

        })
        var _this = this;
        window.onresize = () => {
            _this.tableShow = false
        }

        // 判断table的滚动条是否到达底部
        // this.tableBody = document.getElementById(this.boxId).getElementsByClassName('ant-table-body');
        // this.tableBody[0].onscroll = function () {
        //     // scrollTop + clientHeight == scrollHeight
        //     //  scrollTop为滚动条在Y轴上的滚动距离。
        //     // clientHeight为内容可视区域的高度。
        //     // scrollHeight为内容可视区域的高度加上溢出（滚动）的距离。
        //     if (_this.tableBody[0].scrollTop + _this.tableBody[0].clientHeight == _this.tableBody[0].scrollHeight) {
        //         console.log('我到底部了')
        //         // _this.pagination.current++;
        //         // _this.pageList();
        //     }
        // }
    },
    methods: {
        pageList (defaultRun) {
            if (!this.isRun) {
                this.isRun = true;
                if (defaultRun == 'warehouse') {
                    this.apiUrl = '/in/warehouse/pageList';
                    this.columns = [
                        { title: "仓库编码", dataIndex: "whCode" },
                        { title: "仓库名称", dataIndex: "whName", ellipsis: true, },
                        { title: "负责人", dataIndex: "whPerson", ellipsis: true, },
                        { title: "电话", dataIndex: "whTelephone", ellipsis: true, },
                    ];
                    this.postData = {
                        current: this.pagination.current,
                        size: this.pagination.pageSize,
                        keyWord: this.inputValue,
                    }
                } else {
                    this.postData.current = this.pagination.current
                    this.postData.size = this.pagination.pageSize
                    this.postData['page.current'] = this.pagination.current
                    this.postData['page.size'] = this.pagination.pageSize
                }
                getAction(this.apiUrl, this.postData).then(response => {
                    if (response.code === 200) {
                        const { records, total, current, size } = response.data;
                        let page = {
                            total: total,
                            pageSize: size,
                            current: current
                        }
                        this.pagination = Object.assign(this.pagination, page);
                        console.log("请求地址：", this.apiUrl, this.dynamicData)
                        //返回值处理
                        let val = this.modelVal;
                        let route = this.$route.path;
                        switch (val) {
                            case 'Delivery'://出库类型
                            case 'Warehousing'://入库类型
                                records.forEach(element => {
                                    if (val == 'Delivery') {
                                        this.$set(element, 'category', 2);
                                    } else if (val == 'Warehousing') {
                                        this.$set(element, 'category', 1);
                                    }
                                });
                                break;
                            default:
                                break;
                        }

                        // if (route == '/inventory/bills/purchaseIn' && val == 'warehouse') {
                        //     //表示是库存管理里的采购入库
                        //     this.tableData = response.data;
                        // } else {
                        this.tableData = records;
                        // }

                        this.isRun = false;

                        //库存初期默认选择第一个仓库
                        if (defaultRun == 'warehouse') {
                            console.log('当前选中的仓库', records[0])
                            this.codesName = "warehouseId";
                            this.clickEnter('click', records[0]);
                        }
                    }
                }).catch(error => { });
            }
        },
        showModal () {
            this.tableShow = true;
            this.pageList();
            console.log(this.dynamicData, 123);
            if (this.dynamicData.length > 0) {
                this.codesName = this.dynamicData.code;
                this.boxId = this.dynamicData.code;
            }
            this.$nextTick(() => {
                let w = document.body.clientWidth;//当前可视窗口宽度
                let searchBox = this.$refs.searchWrapper.getBoundingClientRect();
                let searchInput = this.$refs.searchInput.getBoundingClientRect();
                console.log(searchInput, w);
                // console.log('弹出框距离左侧距离：', searchBox.right, w, searchInput)
                if (searchInput.right + 50 >= w) { //右边溢出处理
                    this.$refs.searchWrapper.style.left = -(searchBox.width - searchInput.width) + 'px';
                } else if (searchInput.left < 400) { //左边溢出处理
                    this.$refs.searchWrapper.style.left = 0 + 'px';
                } else {
                    this.$refs.searchWrapper.style.left = - searchInput.width + 'px'
                }
            })
        },
        onclose () {
            this.tableShow = false;
        },
        inputSearch () {
            this.tableShow = true;
            let val = this.dynamicData.val;
            switch (val) {
                case 'supplie'://供应商
                    this.postData.keyWord = this.inputValue;
                    break;
                case 'office'://部门
                    this.postData.officeCode = this.inputValue;
                    break;
                case 'employees'://业务员、请购人、检验
                case 'project'://项目
                case 'currency'://币种
                case 'purchaseType'://采购类型
                case 'saleType'://销售类型
                    this.postData.searchKey = this.inputValue;
                    break;
                case 'crm'://客户名称
                    this.postData.keyWord = this.inputValue;
                    break;
                case 'crmCustomer'://报价单客户名称
                    this.postData.keyWord = this.inputValue;
                    break;
                case 'warehouse'://仓库
                    this.postData.keyWord = this.inputValue;
                    break;
                case 'invoiceType'://发票
                    this.postData.searchKey = this.inputValue;
                default:
                    break;
            }
            //延迟请求
            if (this.setTime) {
                clearTimeout(this.setTime)
            }
            this.setTime = setTimeout(() => {
                this.pageList();
            }, 500)
        },
        clickEnter (type, record) {
            //type == 'click' 表示点击表格事件
            let data = {};
            if (type == 'click') {
                data = Object.assign(record, { codesName: this.codesName })
                this.id = record.id;
            } else {
                data = Object.assign(this.tableData[0], { codesName: this.codesName })
                this.id = this.tableData[0].id;
            }
            this.inputValue = data.name;

            console.log(`${this.dynamicData.name}选中的数据：`, data)
            data.modelVal = this.modelVal;
            this.$emit('clickItem', data);
            this.$refs.inputRef.blur();
            this.onclose();
        },

        checkSearch () {
            let val = this.modelVal;
            switch (val) {
                case 'Delivery'://出库类型
                case 'Warehousing'://入库类型
                    this.apiUrl = '/in/rdStyle/pageStyleList';
                    this.columns = [
                        {
                            title: "名称",
                            dataIndex: "name",
                            align: 'center',
                            scopedSlots: {
                                customRender: "name",
                            },
                        },
                        {
                            title: "编码",
                            align: 'center',
                            dataIndex: "gradeRuleStr",
                            scopedSlots: {
                                customRender: "gradeRuleStr",
                            },
                        },
                        {
                            title: "类别",
                            align: 'center',
                            dataIndex: "category",
                            customRender: (text) => {
                                if (text == 1) {
                                    return '入库';
                                } else if (text == 2) {
                                    return '出库';
                                }
                            },
                        }
                    ];

                    this.postData = {
                        'current': this.pagination.current,
                        'size': this.pagination.pageSize
                    }
                    // 1收2发
                    if (val == 'Delivery') {
                        this.postData.type = 2;
                    } else if (val == 'Warehousing') {
                        this.postData.type = 1;
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
</script>
<style lang="less">
    .all-search-wrapper {
        .inputClass {
            width: 100px;
        }
        .search-wrapper {
            max-height: 350px;
            box-shadow: 2px 2px 10px 2px #e0e0e0;
            position: absolute;
            left: -170px;
            z-index: 100;
            border: 1px solid #a7abb0;
            width: 500px;
        }
        .zzc {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 2;
            width: 100%;
            height: 100vh;
        }
        // .ant-table-wrapper .ant-table-placeholder {
        //     position: static !important;
        //     top: 0;
        // }
        .ant-table-wrapper {
            background: #eee;
        }
        .ant-table-tbody {
            cursor: pointer;
        }
    }
</style>